package com.zsrd.auth.service;

import com.zsrd.auth.domain.SecurityUser;
import com.zsrd.user.domain.SysUser;
import com.zsrd.user.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author LY
 * @ClassName UserServiceImpl
 * @Date 2023/6/10 14:54
 * @Description 用户信息校验
 * @Version 1.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserDetailsService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.getByUsername(s);
        if(sysUser==null){
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        SecurityUser securityUser=new SecurityUser(sysUser);
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<String> roles = sysUserMapper.getListUserById(sysUser.getUserId());
        if(roles.size()>0){
            roles.forEach(r-> authorities.add(new SimpleGrantedAuthority(r)));
        }
        securityUser.setAuthorities(authorities);
        return securityUser;
    }
}
